package com.jinzhi.common.filter;

import com.jinzhi.api.exception.IFastApiException;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.configconsts.wxconsts.LinkConfiggure;
import com.jinzhi.common.utils.*;
import com.jinzhi.common.vo.WxPayConfig;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.type.ApiEnumError;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.chain.Context;
import org.apache.commons.chain.impl.ChainBase;
import org.apache.commons.chain.impl.ContextBase;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/wxApi/jzweb")
public class WXPayControllerDemo extends BaseController {
    @Autowired
    private WxPayConfig wxPayConfig;

    @Autowired
    private ChainBase wxPayOrderTemplateChain, wxPayOrderNotifyTemplateChain;

    @Autowired
    private DictService dictService;

    private static BigDecimal bigDecimal;

    static {
        bigDecimal = new BigDecimal(100);
    }

    private static final String separator = ",";


    @GetMapping("/wxPay")
    @Log("微信支付")
    @ApiOperation("微信支付")
    @RequiresAuthentication
    @Transactional
    @RequiresPermissions("wxApi:jzweb:wxPay")
    public ApiResult<?> wxPay(Integer order_id,String orderIofn) {
        ApiResult apiResult = new ApiResult();
        try {
            //对token信息进行验证
//            int wx_id = this.getClientUser(token).getWxId();
//
//            WxUserinfoDO wxUserinfoDO = wxUserinfoService.selectById(wx_id);
//
//            if (null == wxUserinfoDO) {
//                throw new IFastApiException(ApiEnumError.apiAuthorizationInvalid.getCodeStr());
//            }
            //对order_id进行验证
            if (null == order_id) {
                throw new IFastApiException(ApiEnumError.ORDER_NOT_NULL.getCodeStr());
            }

            //通过uuid生成商户id
            String out_trade_no = UUID.randomUUID().toString().replace("-", "");

            //生成32为随机数
            String randomStringBy = StringUtil.getRandomStringByLength(32);


            //对微信支付所需参数进行收集录入
//            wxPayVo.setAppid(wxPayConfig.getAppId());
//            wxPayVo.setMch_id(wxPayConfig.getMerNo());
//            wxPayVo.setNotify_url(wxPayConfig.getOrdernotify());
//            wxPayVo.setTotal_fee(finallyPayMoney.toString());
//            wxPayVo.setSpbill_create_ip(wxPayConfig.getIp());
//            wxPayVo.setAttach(wxPayVo.getRecharge_id());
//            wxPayVo.setOut_trade_no(out_trade_no);
//            wxPayVo.setNonce_str(randomStringBy);
//            wxPayVo.setTotal_fee(new BigDecimal(wxPayVo.getTotal_fee()).multiply(bigDecimal).setScale(0).toString());
//            wxPayVo.setOpenId(openId);
//            wxPayVo.setLabel(WxPayLabelEnum.order.getTag());
//            wxPayVo.setType(AppEnum.client.getTag());

            //保存order_id至缓存，为后面回调提供
            EhCacheUtil.put(out_trade_no + ":order_id", order_id);

            //创建上下文
            Context context = new ContextBase();

/*            //微信支付对象
            context.put(LinkConfiggure.WX_PAY_VO, wxPayVo);*/
            //固定返回对象
            context.put(LinkConfiggure.API_RESULT, apiResult);
            //订单id
            context.put("order_id", order_id);

            //开始链路
            wxPayOrderTemplateChain.execute(context);
        } catch (Exception e) {
            throw new RuntimeException();
        }
        Map map = new HashMap();
        map.put("type", "wx");
        map.put("wx", apiResult);
        return ApiResult.success(map);
    }


    /**
     * 微信支付回调
     *
     * @param request
     * @return
     */
    @ExceptionHandler(Exception.class)
    @PostMapping("/wxNotify")
    @RequiresPermissions("wxApi:jzweb:wxNotify")
    public String wxNotify(HttpServletRequest request) {
        StringUtil stringUtil = new StringUtil();
        return stringUtil.getWxNotify(request, wxPayOrderNotifyTemplateChain, wxPayConfig);
    }


}
